package com.xiaozhameng.jsp.module.test.controller;

import com.xiaozhameng.jsp.module.test.entity.Student;
import com.xiaozhameng.jsp.module.test.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author xiaozhameng
 */
@Controller
@RequestMapping("/student")
public class StudentHandler {

    @Autowired
    private StudentRepository studentRepository;

    @GetMapping("/findAll")
    public ModelAndView findAll(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("list",studentRepository.findAll());
        return modelAndView;
    }
    //这里简单判断一下选择性跳转到新增还是修改界面
    @GetMapping("/findById/{id}")
    public ModelAndView findById(@PathVariable("id") long id){
        ModelAndView modelAndView = new ModelAndView();
        if (studentRepository.hasId(id)){
            modelAndView.setViewName("updateStudent");
        }else{
            modelAndView.setViewName("addStudent");
        }
        modelAndView.addObject("student",studentRepository.findById(id));
        return modelAndView;
    }
    @PostMapping("/updateStudent")
    public String update(Student student){
        studentRepository.update(student);
        return "redirect:/student/findAll";
    }
    //这里查一下数据库id是否存在，判断是否能提交
    @PostMapping("/addStudent")
    public String add(Student student){
        studentRepository.add(student);
        return "redirect:/student/findAll";
    }
    //应该用deleteMapping，但是a标签里面是get请求，为了搞快点，就直接写了
    @GetMapping("/deleteById/{id}")
    public String deleteById(@PathVariable("id") long id){
        studentRepository.deleteById(id);
        return "redirect:/student/findAll";
    }
}
